﻿using Abp.Domain.Repositories;
using iTextSharp.text;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore.Infrastructure;
using MySqlX.XDevAPI.Common;
using SportsPlatform.Base;
using SportsPlatform.Consts;
using SportsPlatform.Dto.SportBusiness.CompetitionProjec;
using SportsPlatform.Dto.WeChat;
using SportsPlatform.Enums;
using SportsPlatform.Helpers;
using SportsPlatform.Model.SportBusiness;
using SportsPlatform.Query.CompetitionProjec;
using SportsPlatform.Query.WeChat;
using SportsPlatform.WeChat.IWeChat;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static iTextSharp.text.pdf.AcroFields;
using GetCompetitionListDto = SportsPlatform.Dto.SportBusiness.CompetitionProjec.GetCompetitionListDto;

namespace SportsPlatform.WeChat.WeChat
{
    public class WeChatCompetitionService : SportsPlatformAppServiceBase, IWeChatCompetitionService
    {
        private readonly IRepository<Competition, Guid> _competitionRepository;
        private readonly IRepository<RegistrationInfo, Guid> _registrationInfoRepository;
        private readonly IRepository<CompetitionProject, Guid> _competitionProjectRepository;
        private readonly IRepository<CompetitionRuleInfo, Guid> _competitionRuleInfoRepository;
        private readonly IRepository<RuleApplyProject, Guid> _ruleApplyProjectRepository;
        private readonly IRepository<ProjectType, Guid> _projectTypeRepository;
        private readonly IRepository<Project, Guid> _projectRepository;
        private readonly IRepository<Employee, Guid> _employeeRepository;
        private readonly IRepository<CompetitionRuleInfo, Guid> _comptitionRuleRepository;
        public WeChatCompetitionService(IRepository<Competition, Guid> competitionRepository, IRepository<RegistrationInfo, Guid> registrationInfoRepository
        , IRepository<CompetitionProject, Guid> competitionProjectRepository, IRepository<CompetitionRuleInfo, Guid> competitionRuleInfoRepository,
            IRepository<RuleApplyProject, Guid> ruleApplyProjectRepository, IRepository<ProjectType, Guid> projectTypeRepository,
            IRepository<Employee, Guid> employeeRepository,
            IRepository<Project, Guid> projectRepository,
            IHttpContextAccessor context, IRepository<CompetitionRuleInfo, Guid> comptitionRepository) : base(context)
        {
            _competitionRepository = competitionRepository;
            _registrationInfoRepository = registrationInfoRepository;
            _competitionProjectRepository = competitionProjectRepository;
            _competitionRuleInfoRepository = competitionRuleInfoRepository;
            _ruleApplyProjectRepository = ruleApplyProjectRepository;
            _projectTypeRepository = projectTypeRepository;
            _projectRepository = projectRepository;
            _employeeRepository = employeeRepository;
            _comptitionRuleRepository = comptitionRepository;
        }

        /// <summary>
        /// 获取我的赛事列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<PagePagingDto<WeChatCompetitionListDto>> GetMeCompetitionList(GetWeChatCompetitionQuery query)
        {
            PagePagingDto<WeChatCompetitionListDto> result = new PagePagingDto<WeChatCompetitionListDto>();
            try
            {
                List<WeChatCompetitionListDto> reslist = new List<WeChatCompetitionListDto>();
                //分页获取我的报名信息表中有多少个赛事
                //根据赛事ID分组
                var competitionreglist = (await _registrationInfoRepository.GetAllListAsync(r => r.EmployeeId == query.EmployeeId && r.IsDeleted == false))
                .GroupBy(a => new { a.CompetitionId }).Select(a => new { Id = a.Key.CompetitionId }).Skip((query.PageIndex - 1) * query.PageSize).Take(query.PageSize).ToList();

                var competition = await _competitionRepository.GetAllListAsync();
                var projectlist = await _competitionProjectRepository.GetAllListAsync(a => a.IsDeleted == false);
                var registrs = await _registrationInfoRepository.GetAllListAsync(a => a.EmployeeId == query.EmployeeId && a.RegistrationStatus < 3);
                var emp = await _employeeRepository.GetAsync(query.EmployeeId);
                if (competitionreglist.Count > 0)
                {
                    foreach (var item in competitionreglist)
                    {
                        WeChatCompetitionListDto dto = new WeChatCompetitionListDto();
                        //获取赛事信息
                        var com = competition.FirstOrDefault(a => a.Id == item.Id);
                        if (com != null)
                        {
                            dto.Id = com.Id;
                            dto.Name = com.Name;
                            dto.EmployeeName = emp.RealName;

                            var list = new List<CompetitionProjectWeChatDto>();

                            //获取报名信息表中参加的比赛项目
                            var regproject = registrs.Where(a => a.CompetitionId == item.Id);
                            foreach (var reg in regproject)
                            {
                                var comdto = new CompetitionProjectWeChatDto();
                                var p = projectlist.FirstOrDefault(a => a.Id == reg.CompetitionProjectId);
                                if (p != null)
                                {
                                    comdto.CompetitionProjectName = p.Name;
                                    comdto.CompetitionAddress = com.City + "|" + p.Address;
                                    var gameendtime = p.GameBeginTime.Date == p.GameEndTime.Date ? p.GameEndTime.ToString("HH:mm") : p.GameEndTime.ToString("yyyy-MM-dd HH:mm");
                                    comdto.GameTime = $"{p.GameBeginTime.ToString("yyyy-MM-dd HH:mm")} ～{gameendtime}";
                                    comdto.GameTypeName = Enum.GetName(typeof(CompetitionProjectTypeEnum), p.GameType);
                                    comdto.StateStr = Enum.GetName(typeof(CompetitionProjectStateEnum), p.State);
                                    comdto.State = p.State;
                                    list.Add(comdto);
                                }
                            }
                            dto.CompeteInfos = list;
                        }
                        reslist.Add(dto);
                    }

                    result.Data = reslist;
                    result.IsSuccess = true;
                    result.Code = HttpResultCode.Success;
                    result.TotalCount = reslist.Count();
                    result.Message = "查询成功";
                }
                else
                {
                    result.IsSuccess = false;
                    result.Code = HttpResultCode.SqlError;
                    result.Message = "未查询到相关信息！";
                }

            }
            catch (Exception e)
            {
                result.IsSuccess = false;
                result.Code = HttpResultCode.Error;
                result.Message = e.Message.ToString();
            }
            return result;
        }

        /// <summary>
        /// 获取赛事项目信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultDto<WeChatCompetitionProjectDetails>> GetWeChatCompetitionProjectDetails(GetWeChatCompetitionDtoQuery query)
        {
            ResultDto<WeChatCompetitionProjectDetails> resultDto = new ResultDto<WeChatCompetitionProjectDetails>();
            WeChatCompetitionProjectDetails details = new WeChatCompetitionProjectDetails();
            try
            {
                List<WeChatCompetitionProjectlist> projectlists = new List<WeChatCompetitionProjectlist>();

                var competition = await _competitionRepository.GetAsync(query.CompetitionId);
                if (competition.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.NotData;
                    resultDto.Message = "未查询到数据";
                    return resultDto;
                }
                var Rprojects = await _projectRepository.GetAllListAsync(p => p.IsDeleted == false && p.State == 1);
                var RPtypes = await _projectTypeRepository.GetAllListAsync(pt => pt.IsDeleted == false && pt.State == true);
                var projects = await _competitionProjectRepository.GetAllListAsync(p => p.CompetitionId == competition.Id && p.IsDeleted == false && p.State > 0);
                var RuleInfs = await _competitionRuleInfoRepository.GetAllListAsync(r => r.IsDeleted == false && r.State == 1);
                var res = projects.OrderBy(p => Convert.ToDateTime(p.GameBeginTime.ToString("yyyy-MM-dd HH:mm"))).ToList();

                details.Name = competition.Name;
                details.CompetitionAddress = competition.City + "|" + competition.Address;
                details.DetailsAddress = competition.DetailsAddress;
                details.Point = competition.Point;
                details.RegistrationSubmissionTime = competition.SignUpBeginTime.ToString("yyyy.MM.dd") + "-" + competition.SingUpEndTime.ToString("MM.dd");


                if (projects.Count > 0)
                {

                    res.ForEach(p =>
                    {
                        WeChatCompetitionProjectlist weChatProject = new WeChatCompetitionProjectlist();
                        weChatProject.CompetitionRuleInfos = new List<WeChatCompetitionRuleInfo>();
                        weChatProject.Consultant = p.Consultant;

                        var gameendtime = p.GameBeginTime.Date == p.GameEndTime.Date ? p.GameEndTime.ToString("HH:mm") : p.GameEndTime.ToString("yyyy-MM-dd HH:mm");
                        string GameTime = $"{p.GameBeginTime.ToString("yyyy-MM-dd HH:mm")}-{gameendtime}";

                        var gameendtime1 = p.GameBeginTime.Date == p.GameEndTime.Date ? p.GameEndTime.ToString("HH:mm") : p.GameEndTime.ToString("yyyy.MM.dd HH:mm");
                        string GameTime1 = $"{p.GameBeginTime.ToString("yyyy.MM.dd HH:mm")}-{gameendtime}";

                        details.GameTime = GameTime1;
                        weChatProject.GameDateTime = GameTime1;
                        details.GameTime = res.FirstOrDefault().GameBeginTime.ToString("yyyy-MM-dd") + "-" + res.LastOrDefault().GameEndTime.ToString("MM-dd");
                        weChatProject.GameDateTime = GameTime;
                        weChatProject.GameTime = p.GameTime;
                        weChatProject.GroupLimit = p.GroupLimit;
                        weChatProject.Stadium = p.Stadium;
                        weChatProject.Name = p.Name;
                        var project = Rprojects.FirstOrDefault(rp => rp.Id == p.ProjectId);
                        if (!project.IsNullAndEmpty())
                        {
                            var type = RPtypes.FirstOrDefault(pt => pt.Id == project.ProjectTypeID);
                            weChatProject.ProjectType = type.Name;
                        }
                        weChatProject.SignUpLimit = p.SignUpLimit;
                        weChatProject.SensorsMaxNum = p.SensorsMaxNum;
                        weChatProject.TeamMaxUserNum = p.TeamMaxUserNum;
                        weChatProject.TelePhone = p.TelePhone;
                        weChatProject.TeamMaxUserNum = p.TeamMaxUserNum;
                        weChatProject.Id = p.Id;



                        var ruleInfos = RuleInfs.Where(ru => ru.Id == p.CalculationRule || ru.Id == p.PunishmentRule).ToList();
                        if (ruleInfos.Count > 0)
                        {
                            ruleInfos.ForEach(r =>
                            {
                                weChatProject.CompetitionRuleInfos.Add(new WeChatCompetitionRuleInfo
                                {
                                    Content = r.Content,
                                    Type = ((CompetitionRuleInfoTypeEnum)r.Type).GetDescription(),
                                });
                            });
                        }
                        projectlists.Add(weChatProject);
                    });

                    details.Projectlists = projectlists;
                }
                else
                {
                    resultDto.Code = HttpResultCode.NotData;
                    resultDto.Message = "未查询到数据";
                    return resultDto;
                }
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.Message = e.Message;
                return resultDto;
            }
            resultDto.Code = HttpResultCode.Success;
            resultDto.Message = "查询成功";
            resultDto.IsSuccess = true;
            resultDto.Data = details;
            return resultDto;
        }

        /// <summary>
        /// 我的赛事详情
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultDto<WeChatCompetitionDetails>> GetWeChatEmployeeDtoList(GetWeChatEmployeeDtoQuery query)
        {
            ResultDto<WeChatCompetitionDetails> result = new ResultDto<WeChatCompetitionDetails>();
            try
            {
                WeChatCompetitionDetails detail = new WeChatCompetitionDetails();
                var projectlist = (await _competitionProjectRepository.GetAllListAsync(a => a.CompetitionId == query.CompetitionId))
                    .OrderBy(c => c.GameBeginTime).ToList();
                var registrs = await _registrationInfoRepository.GetAllListAsync(a => a.EmployeeId == query.EmployeeId
                && a.CompetitionId == query.CompetitionId
                && a.RegistrationStatus < 3);
                var reg = registrs.Select(a => a.CompetitionProjectId).ToList();
                var emps = await _employeeRepository.GetAllListAsync(e => e.IsDeleted == false);
                var teams = await _registrationInfoRepository.GetAllListAsync(t => t.IsDeleted == false);
                var emp = emps.FirstOrDefault(e => e.Id == query.EmployeeId);
                detail.CompeteIdNo = emp.IDNumber;
                detail.SensorNumber = emp.Sensor;
                detail.CompeteTel = emp.Phone;
                detail.Id = emp.Id;
                detail.Name = emp.RealName;

                if (projectlist.Count > 0)
                {
                    detail.CompetitionProjects = new List<WeChatCompetitionProject>();
                    foreach (var item in projectlist)
                    {
                        WeChatCompetitionProject p = new WeChatCompetitionProject();

                        //等于1为团队赛，等于2为个人赛
                        if (item.GameType == (int)CompetitionProjectTypeEnum.团队接力赛)
                        {
                            var r = registrs.FirstOrDefault(a => a.CompetitionProjectId == item.Id);
                            if (!r.IsNullAndEmpty())
                            {
                                var ts = teams.Where(a => a.CompeteTeamId == r.CompeteTeamId && a.CompetitionId == query.CompetitionId && a.RegistrationStatus < 3).ToList();
                                string CompeteInfoName = "";
                                if (ts.Count > 0)
                                {
                                    foreach (var t in teams)
                                    {
                                        var e = emps.FirstOrDefault(e => e.Id == t.EmployeeId);
                                        if (e != null)
                                        {
                                            CompeteInfoName += e.RealName + "、";
                                        }
                                    }
                                }
                                if (!string.IsNullOrEmpty(CompeteInfoName))
                                {
                                    CompeteInfoName = CompeteInfoName.Substring(0, CompeteInfoName.Length - 1);
                                }
                                p.CompeteInfoName = CompeteInfoName;
                                p.CompeteTeamName = r.CompeteTeamName;
                            }
                            else
                            {
                                p.CompeteInfoName = "";
                                p.CompeteTeamName = "";
                            }
                        }
                        else
                        {

                            p.CompeteInfoName = "";
                            p.CompeteTeamName = "";
                        }
                        p.CompetitionAddress = item.Address;
                        p.CompetitionProjectName = item.Name;
                        var gameendtime = item.GameBeginTime.Date == item.GameEndTime.Date ? item.GameEndTime.ToString("HH:mm") : item.GameEndTime.ToString("yyyy-MM-dd HH:mm");
                        p.GameTime = $"{item.GameBeginTime.ToString("yyyy-MM-dd HH:mm")} ～{gameendtime}";
                        p.GameTypeName = Enum.GetName(typeof(CompetitionProjectTypeEnum), item.GameType);
                        detail.CompetitionProjects.Add(p);
                    };
                    result.Code = HttpResultCode.Success;
                    result.Data = detail; result.Message = "查询成功";
                    result.IsSuccess = true;
                }
                else
                {
                    detail.isSignUp = false;
                    result.Message = "未查询到赛事项目数据";
                }

            }
            catch (Exception e)
            {
                return result;
            }
            return result;
        }


        /// <summary>
        /// 获取赛事比赛列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<PagePagingDto<GetCompetitionListDto>> GetCompetitionList(GetCompentitionProject query)
        {
            var res = new PagePagingDto<GetCompetitionListDto>() { IsSuccess = true, Data = null, TotalCount = 0, TotalPage = 0, Code = HttpResultCode.NotData };
            var list = new List<GetCompetitionListDto>();
            var comprojects = await _competitionProjectRepository.GetAllListAsync(p => p.IsDeleted == false && p.CompetitionId == query.CompetitionId);
            var result = comprojects.Where(r => r.State == 2).ToList();

            var count = result.Count;
            var com = await _competitionRepository.GetAsync(query.CompetitionId);
            var rules = await _comptitionRuleRepository.GetAllListAsync(r => r.IsDeleted == false);

            var projects = await _projectRepository.GetAllListAsync(p => p.IsDeleted == false && p.State == 1);
            var projectTypes = await _projectTypeRepository.GetAllListAsync(ty => ty.IsDeleted == false && ty.State == true);
            if (result.Count > 0)
            {
                foreach (var item in result)
                {
                    var p = new GetCompetitionListDto();
                    p.Id = item.Id;
                    p.Address = item.Address + " | " + item.Stadium;
                    p.GameType = Enum.GetName(typeof(CompetitionProjectTypeEnum), item.GameType);
                    var gameendtime = item.GameBeginTime.Date == item.GameEndTime.Date ? item.GameEndTime.ToString("HH:mm") : item.GameEndTime.ToString("yyyy-MM-dd HH:mm");
                    p.GameDate = $"{item.GameBeginTime.ToString("yyyy-MM-dd HH:mm")} ～{gameendtime}";
                    p.SensorsMaxNum = item.SensorsMaxNum;
                    p.TeamMaxUserNum = item.TeamMaxUserNum;
                    p.Name = item.Name;
                    p.CompetitionId = com.Id;
                    p.CompetitionName = com.Name;
                    p.State = com.State;
                    p.Money = item.IsFree == true ? "0" : item.CostMoney.ToString();
                    var jsrule = rules.FirstOrDefault(r => r.Id == item.CalculationRule);
                    var cfrule = rules.FirstOrDefault(r => r.Id == item.PunishmentRule);
                    p.CalculationRule = jsrule.Content;
                    p.PunishmentRule = cfrule.Content;
                    //获取项目类别
                    var project = projects.FirstOrDefault(p => p.Id == item.ProjectId);
                    if (project != null)
                    {
                        var type = projectTypes.FirstOrDefault(p => p.Id == project.ProjectTypeID);
                        if (type != null)
                        {
                            p.ProjectType = type.Name;
                        }
                    }
                    list.Add(p);
                }
                res.TotalCount = count;
                res.Code = HttpResultCode.Success;
                res.Data = list;
                res.IsSuccess = true;
                res.Message = "查询成功";
            }
            else
            {
                res.IsSuccess = false;
                res.Code = HttpResultCode.NotData;
                res.Message = "未查询到数据";
                res.Data = null;
            }
            return res;
        }

    }
}
